package com.aaron.android.battery;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class DownloadFile extends AsyncTask<String, Integer, String> {
	private final static String TAG = "DownloadFile";
	private File _saveFile = Environment.getExternalStorageDirectory();
	private ProgressDialog _progressDialog;

	public DownloadFile(String savePath, ProgressDialog progressDialog) {
		_saveFile = new File(savePath);
		_progressDialog = progressDialog;
	}

	@Override
	protected String doInBackground(String... urls) {

		try {
			URL url = new URL(urls[0]);
			URLConnection conn = url.openConnection();
			conn.connect();

			int fileLength = conn.getContentLength();

			InputStream input = new BufferedInputStream(url.openStream());
			OutputStream output = new FileOutputStream(_saveFile);

			byte data[] = new byte[1024];
			long total = 0;
			int count;
			while ((count = input.read(data)) != -1) {
				total += count;
				publishProgress((int) (total * 100 / fileLength));
				output.write(data, 0, count);
			}

			output.flush();
			output.close();
			input.close();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
		}

		return null;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		_progressDialog.show();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		_progressDialog.setProgress(values[0]);
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		_progressDialog.dismiss();
		if (downloadCompletedListener != null) {
			Log.d(TAG, "Download completed.");
			downloadCompletedListener.OnDownloadCompleted(_saveFile);
		}
	}

	private OnDownloadCompletedListener downloadCompletedListener = null;

	public void setDownloadCompletedListener(
			OnDownloadCompletedListener listener) {
		downloadCompletedListener = listener;
	}
}
